import React, {useState} from "react"
import {Alert, Button, Form, Input} from "antd"
import JSEncrypt from "jsencrypt"
import {UserOutlined} from '@ant-design/icons'
import {postJSON} from "../../shared/server/index"
import "./login.less"
import AvatarLoader from "../../shared/libs/avatar-loader"
import bg01 from "../../images/login/bg01.jpg"
import bg02 from "../../images/login/bg02.jpg"
import bg03 from "../../images/login/bg03.jpg"
import bg04 from "../../images/login/bg04.jpg"
import bg05 from "../../images/login/bg05.jpg"
import bg06 from "../../images/login/bg06.jpg"
import bg07 from "../../images/login/bg07.jpg"
import logo from "../../images/login/logo.png"
import cs from "classnames"
import useTheme from "../../shared/libs/antd-theme"

import {HOST, PUBLIC_KEY} from "../../shared/project-config"
import KeyOutlined from "@ant-design/icons/lib/icons/KeyOutlined";
import LockOutlined from "@ant-design/icons/lib/icons/LockOutlined";


const inputSize = 'default'

const labelWidth = 0
const formItemLayout = {
	labelCol: {
		xs: {span: labelWidth},
		sm: {span: labelWidth},
	},
	wrapperCol: {
		xs: {span: 24},
		sm: {span: 24},
	},
}


const LoginPage = ({history}) => {
	let gotoUrl = undefined
	const [initData, $initData] = useState(() => {
		return {}
	})
	const [avatar, $avatar] = useState(undefined)
	const [submitting, setSubmitting] = useState(false)
	const [serverMessage, $serverMessage] = useState(undefined)
	const [form] = Form.useForm()
	const [vCodePath, $vCodePath] = useState(`${HOST}/management/verificationCode?t=${new Date().getTime()}`)
	const {getBackground} = useTheme()
	const {cls, img, color} = getBackground() || {};

	const onRefreshVCode = () => {
		$vCodePath(`${HOST}/management/verificationCode?t=${new Date().getTime()}`)
		form.setFieldsValue({verificationCode:''})
	}

	const onLoginNameChange = (event) => {
		const localAvatar = localStorage.getItem(`meinian_${event.target.value}_avatar`)
		if (localAvatar && localAvatar !== 'null') {
			$avatar(`/avatar/${localAvatar}`)
		} else {
			$avatar(undefined)
		}
	}

	const onSubmit = () => {
		form.validateFields()
			.then(login)
	}

	const login = ({password, userName, verificationCode}) => {
		const encrypt = new JSEncrypt();
		encrypt.setPublicKey(PUBLIC_KEY);
		const passwordSecret = encrypt.encrypt(password);
		const postData = {
			encrypt: true,
			loginName: userName,
			password: passwordSecret,
			verificationCode: verificationCode
		}
		setSubmitting(true)
		postJSON("/management/login", postData, true)
			.then(result => {
				if (!result) return;
				const avatar = result.avatar
				if (avatar) {
					localStorage.setItem(`meinian_${userName}_avatar`, avatar)
				}
				if (result && result.activated) {
					if (result.role === 'salesman_manager') {
						gotoUrl = "/app/account/salesman"
					} else {
						gotoUrl = "/app/product"
					}
				} else {
					gotoUrl = "/active"
				}
			})
			.catch(e => {
				if (e && e.message) {
					$serverMessage(e.message)
				}
			}).finally(() => {
			onRefreshVCode()
			setSubmitting(false)
			if (gotoUrl) {
				history.push(gotoUrl)
			}
		})
	}


	return (
		<div className={'login-page'}>
			<div className={cs('login-page-bg', cls)}>
				<div className={'mask'}/>
			</div>
			<div className="container">
				<div className="header">
					<img src={img || bg04}/>
					<div className={'header-content'}>
						<h1>美联健康</h1>
						<h2>业务报价辅助系统</h2>
						<div className={'ld2-avatar'}>
							<AvatarLoader style={{
								width: '104',
								height: '104'
							}} src={`${avatar}`}/>
						</div>
					</div>
					<div className={'login-error-message'}>
						{
							!serverMessage
								? undefined
								: <Alert message={serverMessage} type="error" showIcon className={'zr-login-message'}/>
						}
					</div>
				</div>
				<div className="content" style={{background: color}}>
					<input type="text" style={{display: 'none'}}/>
					<input type="password" style={{display: 'none'}}/>
					<Form {...formItemLayout} className="login-form" form={form} initialValues={initData} autoComplete="off">
						<Form.Item name={'userName'}
						           validateFirst={true}
						           rules={[{required: true, message: '登录名/手机号码必须填写'}]}>
							<Input size={inputSize}
							       autoComplete="off"
							       onChange={onLoginNameChange}
							       prefix={<UserOutlined/>}
							       onPressEnter={onSubmit}
							       placeholder="登录名或手机号"/>
						</Form.Item>

						<Form.Item name={'password'}
						           validateFirst={true}
						           rules={[{required: true, message: '登录密码必须填写'}]}>
							<Input.Password size={inputSize}
							                autoComplete="new-password"
							                prefix={<KeyOutlined/>}
							                onPressEnter={onSubmit}
							                placeholder="登录密码"/>
						</Form.Item>
						<Form.Item>
							<Form.Item name={'verificationCode'}
							           noStyle
							           validateFirst={true}
							           rules={[{required: true, message: '验证密码必须填写'}]}>
								<Input
									allowClear
									size={inputSize}
									placeholder="验证码"
									prefix={<LockOutlined/>}
									maxLength={4}
									onPressEnter={onSubmit}
									className={'verification-code-input'}/>
							</Form.Item>
							<img src={vCodePath} alt={''} onClick={onRefreshVCode}/>
						</Form.Item>
					</Form>
					<div>
						<Button
							onClick={onSubmit}
							loading={submitting}
							size="large" type="primary" style={{width: 180, borderRadius: '4px'}}>
							{submitting ? '' : '立即登录'}
						</Button>
					</div>
				</div>
			</div>

		</div>
	)
}

export default LoginPage